import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getTime } from '@/utils/auth'
import router from '@/router'

const ChekTimeOut = () => {
  const newTime = Date.now()
  const oldTime = getTime()
  return newTime - oldTime > 7200000
}

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    if (ChekTimeOut()) {
      store.commit('user/removeToken')
      router.push({ name: 'login' })
      return Promise.reject(new Error('令牌已失效'))
    }
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(res => {
  const { message, success, data } = res.data

  if (success) {
    // 必须要有返回值，否知拿不到数据
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, err => {
  if (err.response && err.response.data && err.response.data.code === 10002) {
    store.commit('user/removeToken')
    err.message = '无效令牌，请重新登录'
    router.push('/login')
  }
  Message.error(err.message)
  // 网络错误
  return Promise.reject(new Error(err.message))
})

export default service
